<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="header">
			<view class="nav-bar">
				<view class="nav-left" @click="goBack">
					<image src="/static/my/首页.png" class="nav-icon"></image>
				</view>
				<text class="nav-title">个人信息</text>
				<view class="nav-right"></view>
			</view>
		</view>

		<!-- 用户信息展示 -->
		<view class="user-info-section">
			<view class="info-item">
				<text class="label">头像</text>
				<view class="avatar-container" @click="changeAvatar">
					<image :src="userInfo.avatar" class="avatar-img" mode="aspectFill"></image>
					<view class="avatar-edit">
						<image src="/static/my/组 9(4).png" class="edit-icon"></image>
					</view>
				</view>
			</view>

			<view class="info-item" @click="editName">
				<text class="label">姓名</text>
				<view class="value-container">
					<text class="value">{{ userInfo.name || '请完善个人信息' }}</text>
					<image src="/static/my/收起箭头小 拷贝.png" class="arrow-icon"></image>
				</view>
			</view>

			<view class="info-item" @click="editPhone">
				<text class="label">手机号</text>
				<view class="value-container">
					<text class="value">{{ userInfo.phone || '未设置' }}</text>
					<image src="/static/my/收起箭头小 拷贝.png" class="arrow-icon"></image>
				</view>
			</view>
		</view>

		<!-- 操作提示 -->
		<view class="tip-section">
			<view class="tip-content">
				<image src="/static/my/组 9(3).png" class="tip-icon"></image>
				<text class="tip-text">点击各项信息可进行修改</text>
			</view>
		</view>
	</view>
</template>

<script>
	import IdentityAPI from '@/api/identity.js'
	import authManager from '@/utils/auth.js'

	export default {
		data() {
			return {
				// 用户信息
				userInfo: {
					avatar: '/static/my/tomcat-plus.png',
					name: '',
					phone: ''
				},
				// 用户ID
				userId: null
			}
		},
		onLoad() {
			// 获取用户ID
			this.userId = authManager.getUserInfo()?.userId
			if (!this.userId) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				})
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
				return
			}
			
			this.loadUserInfo()
		},
		onShow() {
			// 页面显示时刷新用户信息
			this.loadUserInfo()
		},
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack()
			},

			// 加载用户信息
			async loadUserInfo() {
				try {
				// 获取用户完整信息（包括身份认证信息）
				const response = await IdentityAPI.getUserProfile(this.userId)
				console.log('个人信息页面 - 用户完整信息:', response)
				console.log('个人信息页面 - 响应数据结构:', {
					hasResponse: !!response,
					hasData: !!(response && response.data),
					dataKeys: response && response.data ? Object.keys(response.data) : [],
					nameValue: response && response.data ? response.data.name : 'undefined',
					phoneValue: response && response.data ? response.data.phone : 'undefined'
				})
					
					if (response.data) {
						this.userInfo = {
							avatar: response.data.avatar || '/static/my/tomcat-plus.png',
							name: response.data.name || '',
							phone: response.data.phone || ''
						}
					}
				} catch (error) {
					console.error('加载用户信息失败:', error)
					// 如果获取完整信息失败，尝试获取基本信息
					try {
						const basicResponse = await IdentityAPI.getUserInfo(this.userId)
						if (basicResponse.data) {
							this.userInfo = {
								avatar: basicResponse.data.avatar || '/static/my/tomcat-plus.png',
								name: basicResponse.data.name || '',
								phone: basicResponse.data.phone || ''
							}
						}
					} catch (basicError) {
						console.error('加载基本信息也失败:', basicError)
						uni.showToast({
							title: '加载用户信息失败',
							icon: 'none'
						})
					}
				}
			},

			// 修改头像
			changeAvatar() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['camera', 'album'],
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0]
						this.uploadAvatar(tempFilePath)
					},
					fail: (err) => {
						console.error('选择图片失败:', err)
						uni.showToast({
							title: '选择图片失败',
							icon: 'none'
						})
					}
				})
			},

			// 上传头像
			async uploadAvatar(filePath) {
				try {
					uni.showLoading({
						title: '上传中...'
					})

					// 这里应该上传到服务器，暂时使用本地路径
					const avatarUrl = filePath

					// 更新头像
					await IdentityAPI.updateAvatar(this.userId, avatarUrl)

					// 更新本地显示
					this.userInfo.avatar = avatarUrl

					uni.hideLoading()
					uni.showToast({
						title: '头像更新成功',
						icon: 'success'
					})

				} catch (error) {
					console.error('上传头像失败:', error)
					uni.hideLoading()
					uni.showToast({
						title: error.message || '上传失败',
						icon: 'none'
					})
				}
			},

			// 编辑姓名
			editName() {
				uni.showModal({
					title: '修改姓名',
					editable: true,
					placeholderText: '请输入姓名',
					success: (res) => {
						if (res.confirm && res.content) {
							this.updateName(res.content.trim())
						}
					}
				})
			},

			// 更新姓名
			async updateName(name) {
				if (!name) {
					uni.showToast({
						title: '姓名不能为空',
						icon: 'none'
					})
					return
				}

				try {
					uni.showLoading({
						title: '更新中...'
					})

					await IdentityAPI.updateName(this.userId, name)

					// 更新本地显示
					this.userInfo.name = name

					uni.hideLoading()
					uni.showToast({
						title: '姓名更新成功',
						icon: 'success'
					})

				} catch (error) {
					console.error('更新姓名失败:', error)
					uni.hideLoading()
					uni.showToast({
						title: error.message || '更新失败',
						icon: 'none'
					})
				}
			},

			// 编辑手机号
			editPhone() {
				uni.showModal({
					title: '修改手机号',
					editable: true,
					placeholderText: '请输入手机号',
					success: (res) => {
						if (res.confirm && res.content) {
							this.updatePhone(res.content.trim())
						}
					}
				})
			},

			// 更新手机号
			async updatePhone(phone) {
				if (!phone) {
					uni.showToast({
						title: '手机号不能为空',
						icon: 'none'
					})
					return
				}

				// 手机号格式验证
				const phoneRegex = /^1[3-9]\d{9}$/
				if (!phoneRegex.test(phone)) {
					uni.showToast({
						title: '手机号格式不正确',
						icon: 'none'
					})
					return
				}

				try {
					uni.showLoading({
						title: '更新中...'
					})

					await IdentityAPI.updatePhone(this.userId, phone)

					// 更新本地显示
					this.userInfo.phone = phone

					uni.hideLoading()
					uni.showToast({
						title: '手机号更新成功',
						icon: 'success'
					})

				} catch (error) {
					console.error('更新手机号失败:', error)
					uni.hideLoading()
					uni.showToast({
						title: error.message || '更新失败',
						icon: 'none'
					})
				}
			}
		}
	}
</script>

<style scoped>
	.container {
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	/* 顶部导航栏 */
	.header {
		background: linear-gradient(135deg, #3183FB 0%, #3183FB 100%);
		padding-top: 20rpx;
	}

	.nav-bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx 30rpx;
	}

	.nav-icon {
		width: 48rpx;
		height: 48rpx;
	}

	.nav-title {
		color: white;
		font-size: 36rpx;
		font-weight: bold;
		flex: 1;
		text-align: center;
	}

	/* 用户信息区域 */
	.user-info-section {
		background-color: white;
		margin: 20rpx;
		border-radius: 20rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
	}

	.info-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.info-item:last-child {
		border-bottom: none;
	}

	.label {
		font-size: 30rpx;
		color: #333;
		font-weight: 500;
	}

	.avatar-container {
		position: relative;
		width: 100rpx;
		height: 100rpx;
	}

	.avatar-img {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
	}

	.avatar-edit {
		position: absolute;
		bottom: 0;
		right: 0;
		width: 32rpx;
		height: 32rpx;
		background-color: #3183FB;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.edit-icon {
		width: 20rpx;
		height: 20rpx;
	}

	.value-container {
		display: flex;
		align-items: center;
		gap: 16rpx;
	}

	.value {
		font-size: 28rpx;
		color: #333;
	}

	.arrow-icon {
		width: 24rpx;
		height: 24rpx;
	}

	/* 操作提示 */
	.tip-section {
		margin: 20rpx;
	}

	.tip-content {
		background-color: #e6f7ff;
		border-radius: 20rpx;
		padding: 30rpx;
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.tip-icon {
		width: 40rpx;
		height: 40rpx;
	}

	.tip-text {
		color: #1890ff;
		font-size: 28rpx;
		font-weight: 500;
	}
</style>